package com.lzkj.baotouhousingfund.http;

import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;

/**
 * @author Chengs
 * @ClassName: RetryWhenProcess
 * @Description: 重试请求操作
 * @date 2018/3/8 16:52
 */
public class RetryWhenProcess implements Function<Observable<? extends Throwable>, Observable<?>> {

    private long mInterval;

    public RetryWhenProcess(long interval) {
        mInterval = interval;
    }

    @Override
    public Observable<?> apply(final Observable<? extends Throwable> observable) throws Exception {
        return observable.flatMap((Function<Throwable, ObservableSource<?>>) throwable ->
                observable.flatMap((Function<Throwable, ObservableSource<?>>) throwable12 -> {
                    if (throwable12 instanceof UnknownHostException) {
                        return Observable.error(throwable12);
                    }
                    return Observable.just(throwable12).zipWith(Observable.range(1, 5),
                            (throwable1,
                             integer) ->
                                    integer).flatMap((Function<Integer, ObservableSource<?>>)
                            retryCount -> Observable.timer((long) Math.pow(mInterval, retryCount),
                                    TimeUnit.SECONDS));
                }));
    }
}